﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace GPriceTransfer
{
    public partial class Transfer : Form
    {
        public Transfer()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'gPriceCollect_DataDataSet.tb_1_1_data' table. You can move, or remove it, as needed.
            DataTable dtWebSite = BizDAL.web_site.GetList("", "");
            this.cboParentClass.DisplayMember = "name";
            this.cboParentClass.ValueMember = "site_id";
            this.cboParentClass.DataSource = dtWebSite;

            this.cboParentClass.SelectedIndex = 0;
            
            //this.tb_1_1_dataTableAdapter.Fill(this.gPriceCollect_DataDataSet.tb_1_1_data);
            //// TODO: This line of code loads data into the 'gPriceWebDataSet.Category' table. You can move, or remove it, as needed.
            //this.categoryTableAdapter.Fill(this.gPriceWebDataSet.Category);
            //// TODO: This line of code loads data into the 'gPriceWebDataSet.Child_Class' table. You can move, or remove it, as needed.
            ////this.child_ClassTableAdapter.Fill(this.gPriceWebDataSet.Child_Class);
            //this.categoryTableAdapter.Fill(this.gPriceWebDataSet.Category);
            //// TODO: This line of code loads data into the 'gPriceWebDataSet.Child_Class' table. You can move, or remove it, as needed.
            //this.child_ClassTableAdapter.Fill(this.gPriceWebDataSet.Child_Class);
            //// TODO: This line of code loads data into the 'gPriceCollect_DataDataSet.tb_1_1_data' table. You can move, or remove it, as needed.
            //this.tb_1_1_dataTableAdapter.Fill(this.gPriceCollect_DataDataSet.tb_1_1_data);

        }


        //<?xml version='1.0' encoding='utf-8' ?><content><![CDATA[<br>        <br>        <table width="520" border="0" bgcolor="#BBDFFF" cellspacing="1" cellpadding="2">                    <tr>             <td width="110" bgcolor="#EEF7FF" height="25"><b>　学员对象：</b></td>            <td width="399" bgcolor="#FFFFFF" height="25">企业总经理、采购总经理、工厂厂长、ERP经理、供应链经理、采购总监、采购经理、供应链经理、采购主管、计划经理、物流经理、制造经理、营运总监、经理、材料控制主管、物资管理、财务部总监、供应部门及其参与跨职能团队相关主管人员。</td></tr>                    <tr>             <td bgcolor="#EEF7FF" height="27"><b>　课程目的：</b></td>            <td bgcolor="#FFFFFF" height="27" style="word-break:break-all;">1、了解仓储库存管理与WMS、综合运输管理<br>2、了解供应链物流网络构建及信息管理<br>3、客户服务管理及客户服务的绩效考核<br>4、如何管理3PL与4PL<br></td></tr>                    <tr>             <td bgcolor="#EEF7FF" height="25"><b>　课程内容：</b></td>            <td bgcolor="#FFFFFF" height="25">第一部份企业经营目标与供应链战略<br>一、物流管理的发展<br>二、供应链时代的到来<br>三、企业供应链战略和物流规划<br>第二部份企业物流控制与供应链竞争<br>一、企业在产业中竞争优势分析<br>二、构建企业在供应链中领导地位<br>三、供应链的协作与外包<br>第三部份以客户为中心的物流服务策略<br>一、以客户为中心的供应链战略和理念<br>二、供应链环境下的客户服务管理<br>三、提升物流客户服务的手段<br>四、供应链成本核算<br>五、物流绩效衡量<br>六、供应链绩效衡量<br>第四部分供应链网络设计<br>一、供应链分销组织<br>二、供应链发展趋势分析<br>三、供应链设计的原则、步骤与策略<br>四、供应链物流网络系统的设计<br>五、全球供应链管理系统的设计<br>第五部分订单管理与信息系统<br>一、定义订单处理过程<br>二、订单处理举例<br>三、影响订单处理时间的其他因素<br>四、物流信息系统<br>五、信息系统举例第六部分延迟策略与物流增值服务<br>一、延迟策略的内涵与意义<br>二、物流服务创新<br>三、流通加工技术与方法<br>四、物流服务流程优化<br>五、物料处理作业合理化与标准化建设<br>第七部分实物配送与电子商务交付<br>一、供应链环境下的实物配送职能<br>二、各种运输方式及其特点<br>三、实物配送流程优化<br>四、网络时代的配送<br>五、实现电子商务交付的手段与方法<br>第八部分售后服务与仓储管理<br>一、CRM的定义<br>二、供应链仓储管理战略<br>三、仓储优化管理<br>第九部分如何管理3PL与4PL<br>一、物流社会化的趋势<br>二、物流社会化形态<br>三、第三方物流概述<br>四、第三方物流的类型<br>五、影响第三方物流需求决策的因素<br>六、第三方物流和第四方物流<br>七、物流成本分析<br>八、物流成本控制方法<br>九、物流成本控制策略<br>十、不同经济主体物流成本控制<br></td></tr>                  <tr>     <td bgcolor="#EEF7FF" height="27"><b>　开课城市简介：</b></td>     <td bgcolor="white">广东省广州市天河区龙口东路19号悦华大厦</td>    </tr>                    <tr>             <td bgcolor="#EEF7FF" height="27"><b>　授课时间：</b></td>            <td bgcolor="#FFFFFF" height="27">2007-08-11</td></tr>                    <tr>             <td bgcolor="#EEF7FF" height="25"><b>　其他信息：</b></td>            <td bgcolor="#FFFFFF" height="25">包含讲义、听课费、午餐、茶点等</td></tr>                    <tr>            <td bgcolor="#EEF7FF" height="26"><b>　联系方式：</b></td>            <td bgcolor="#FFFFFF" height="26">      010-51298009转8008、8011 程小姐、郭小姐    </td>          </tr>          <tr>             <td colspan="2" bgcolor="#EEF7FF">       <a href="signup.asp?id=24741" target="_blank">     <img src="/image/baoming.gif" width="171" height="59" border="0" alt="报名" align="left" hspace="10"     ></a>     <a href="/ykt/onlinepay.htm" target="_blank">     <img src="image/wy.bmp" alt="点击这里在线购买" border="0" /></a>     <script type="text/javascript"><!--  google_ad_client = "pub-4201802229722874";  google_ad_width = 180;  google_ad_height = 60;  google_ad_format = "180x60_as_rimg";  google_cpa_choice = "CAAQmf6ujAIaCB81TMYLztcDKO3M93MwAA";  google_ad_channel = "";  //-->  </script>  <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">  </script>    </td>          </tr>        </table>        <div align="center"></div>      <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#EEF7FF">          <tr>             <td valign="middle"><div align="center"><font color="#FF0000">【<a href="sendfriend.asp?id=&lx=kcxx">推荐给朋友</a>】　【<a href="javascript:print()">打               印</a>】　【<a href="javascript:window.close()">关闭窗口</a>】　【<a href="#">双击自动滚屏</a>】</font></div></td>          </tr>      </table>]]></content>
        private void btnTransfer_Click(object sender, EventArgs e)
        {
            this.TranslateCollectData(this.cboParentClass.SelectedValue.ToString(),this.cboParentClass.Text,this.cboChildClass.SelectedValue.ToString());
            this.TranslateShowData();
            MessageBox.Show(" 转换完毕");

        }
        /// <summary>
        /// 转换采集来的数据
        /// </summary>
        private void TranslateCollectData(string websiteValue,string websiteText,string plugInValue)
        {
            //得到分类数据
            DataTable dtCate = BizDAL.Category.GetList("", "");
            //首先从源库中得到数据
            DataTable dtData = this.GetData(websiteValue,plugInValue);
            string[] connInsert = new string[dtData.Rows.Count];
            for (int i = 0; i < dtData.Rows.Count; i++)
            {
                DataRow dr = dtData.Rows[i];
                //得到详细信息
                string detail = dr["detail"].ToString();
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(detail);
                XmlNodeList nodes = doc.GetElementsByTagName("content");
                XmlNode root = doc.DocumentElement;
                var cate = FindCategory(root["category"].InnerText, dtCate);
                var typename = root["category"].InnerText;
                var opendate = root["opendate"].InnerText;
                var address = root["address"].InnerText;
                var presideunit = root["presideunit"].InnerText;
                var objective = root["object"].InnerText;
                var teacher = root["teacher"].InnerText;
                var contact = root["contact"].InnerText;
                var srcweb = websiteText;
                //var benefit = root["benefit"].InnerText;
                var introduction = "";

                string tcontent = string.Empty;
                foreach (XmlNode node in nodes)
                {
                    tcontent = node.InnerText;

                }
                //修改价格，由于价格可能有些非法字符
                string oripricevar = dr["original_price"].ToString();
                string propricevar = dr["sale_price"].ToString();
                string oripricemon = TranslateMoney(dr["original_price"].ToString());
                string propricemon = TranslateMoney(dr["sale_price"].ToString());
                //插入详细信息数据到本库中
                Guid g = Guid.NewGuid();
                string gg = g.ToString();

                string strIns = string.Format("INSERT INTO [OPENCLASS] ([oc_id], [type],[typename], [title], [originalpricevar], [promotepricevar], [originalpricemon], [promotepricemon], [teacher], [address], [presideunit], [opendate], [contact], [benefit],[imagepath],[url],[brand],[srcweb],[introduction],[recommindex]) " +
                    " VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', {6}, {7}, '{8}', '{9}', '{10}', '{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}');",
                    g, cate, typename, dr["title"].ToString(), oripricevar, propricevar, oripricemon, propricemon,teacher, address, presideunit, opendate, contact, "", dr["image_path"], dr["url"], dr["brand"], srcweb, introduction, 1);
                connInsert[i] = strIns;
                Longbow.Data.DBAccess.CreateDB().ExecuteNonQuery(strIns);
                //插入数据到关键字表中：目前有下列关键字：标题，价格，顾问，培训机构，类别
                strIns = string.Format("insert into Biz_Keywords values('{0}','{1}')", g, dr["title"]);
                Longbow.Data.DBAccess.CreateDB().ExecuteNonQuery(strIns);
                strIns = string.Format("insert into Biz_Keywords values('{0}','{1}')", g, propricevar);
                if (propricevar.Trim() != string.Empty)
                    Longbow.Data.DBAccess.CreateDB().ExecuteNonQuery(strIns);
                strIns = string.Format("insert into Biz_Keywords values('{0}','{1}')", g, teacher);
                if (teacher.Trim() != string.Empty)
                    Longbow.Data.DBAccess.CreateDB().ExecuteNonQuery(strIns);
                strIns = string.Format("insert into Biz_Keywords values('{0}','{1}')", g, presideunit);
                if (presideunit.Trim() != string.Empty)
                    Longbow.Data.DBAccess.CreateDB().ExecuteNonQuery(strIns);
                strIns = string.Format("insert into Biz_Keywords values('{0}','{1}')", g, typename);
                if (presideunit.Trim() != string.Empty)
                    Longbow.Data.DBAccess.CreateDB().ExecuteNonQuery(strIns);

            }
            //Longbow.Data.DBAccess.CreateDB(System.Configuration.ConfigurationManager.ConnectionStrings["GPrice"]).ExecuteNonQuery(connInsert[0]);
            //转换完毕后，更新标志到原来数据库中
            //BizDAL.digger_plugin dp = new BizDAL.digger_plugin();
            //dp.run_status = 2;
            //dp.UpdatePartial();

        }
        private object FindCategory(string p, DataTable dtCate)
        {
            string ret = "5482576a-43d0-41ec-91a7-986e72b71b9c";
            for (int i = 0; i < dtCate.Rows.Count; i++)
            {
                DataRow drv = dtCate.Rows[i];
                if (drv["cat_name"].ToString() == p)
                {
                    ret = drv["cat_id"].ToString();
                    break;
                }
            }
            return ret;
        }

        private string TranslateMoney(string p)
        {
            char[] vp = p.ToCharArray();
            string temp=string.Empty;
            foreach (Char v in vp)
            {
                //如果是数字，则记录下来
                if (Char.IsDigit(v))
                {
                    temp += v.ToString();
                }

            }
            //p = p.Replace("￥", string.Empty);
            //p = p.Replace("", string.Empty);
            if (temp == string.Empty) temp = "0";
            return temp;
        }

        private string FindCategory(string p)
        {
            string ret = "5482576a-43d0-41ec-91a7-986e72b71b9c";
            for (int i = 0; i < this.cboChildClass.Items.Count; i++)
            {
                DataRowView drv = (DataRowView)this.cboChildClass.Items[i];
                if (drv["cat_name"].ToString() == p)
                {
                    ret = drv["cat_id"].ToString();
                    break;
                }
            }
            return ret;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            //根据所选择的网站和插件，选择数据
            this.dgv.DataSource = this.GetData(this.cboParentClass.SelectedValue.ToString(),this.cboChildClass.SelectedValue.ToString());
        }

        private DataTable GetData(string parentClassValue,string childClassValue)
        {
             string urlTableName = string.Format("tb_{0}_{1}_url", parentClassValue, childClassValue);
            string commentTableName = string.Format("tb_{0}_{1}_comment", parentClassValue, childClassValue);
            string dataTableName = string.Format("tb_{0}_{1}_data", parentClassValue, childClassValue);
            BizDAL.tb_data tbdata = new BizDAL.tb_data(dataTableName,urlTableName);
            return tbdata.Select();
       }

        private void parCClass_IDToolStripTextBox_Click(object sender, EventArgs e)
        {

        }

        private void btnTransferDisplayData_Click(object sender, EventArgs e)
        {
            DateTime dtStart = DateTime.Now;
            //插入数据到搜索数据表中
            string strIns = string.Empty;
            //得到有重复课程的数据
            DataTable dtOpenClass = BizDAL.OPENCLASS.GetDuplicateData();
            for (int i = 0; i < dtOpenClass.Rows.Count; i++)
            {
                //循环读取课程数据
                DataRow drDup = dtOpenClass.Rows[i];
                DataTable cheapestClass = BizDAL.OPENCLASS.GetCheapestData(drDup["title"].ToString().Replace("'","''"));
                DataRow dr = cheapestClass.Rows[0];
                if (Convert.ToInt16(drDup["counter"]) == 1)
                {
                    //如果是1，说明没有同类数据，直接插入到searchcontent表中
                    strIns = string.Format("INSERT INTO [SearchContent] ([oc_id], [type],[typename], [title], [promotepricevar], [promotepricemon], [presideunit], [url],[srcweb],[introduction],[recommindex],[counter]) " +
                                        " VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', {5}, '{6}', '{7}', '{8}', '{9}', '{10}',{11});",
                                        dr["oc_id"], dr["type"], dr["typename"], dr["title"], dr["promotepricevar"], dr["promotepricemon"], dr["presideunit"], dr["url"], dr["srcweb"], dr["introduction"], dr["recommindex"], drDup["counter"]);
                    Longbow.Data.DBAccess.CreateDB().ExecuteNonQuery(strIns);
                }
                else if (Convert.ToInt16(drDup["counter"]) > 1)
                {
                    //如果大于1，则找出最小价格的那条数据
                    strIns = string.Format("INSERT INTO [SearchContent] ([oc_id], [type],[typename], [title], [promotepricevar], [promotepricemon], [presideunit], [url],[srcweb],[introduction],[recommindex],[counter]) " +
                                         " VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', {5}, '{6}', '{7}', '{8}', '{9}', '{10}',{11});",
                                         dr["oc_id"], dr["type"], dr["typename"], dr["title"], dr["promotepricevar"], dr["promotepricemon"], dr["presideunit"], dr["url"], dr["srcweb"], dr["introduction"], dr["recommindex"], drDup["counter"]);
                    Longbow.Data.DBAccess.CreateDB().ExecuteNonQuery(strIns);
                }
            }
            DateTime dtEnd = DateTime.Now;
            MessageBox.Show(" 转换完毕,共耗时" + dtEnd.Subtract(dtStart).TotalSeconds + "秒");
        }
        private void TranslateShowData()
        {
            //读取format格式
            try
            {
                DataTable dtClass = BizDAL.Child_Class.GetList("", "");
                string strFormat = string.Empty;
                if (dtClass.Rows.Count > 0)
                {
                    strFormat = dtClass.Rows[0]["CClass_Format"].ToString();
                }
                //读取数据，
                string openClassID = string.Empty;
                DataTable dtData = BizDAL.OPENCLASS.GetList("", "");
                if (dtData.Rows.Count > 0)
                {
                    string detailData = string.Empty;
                    //循环读取行列，数据
                    foreach (DataRow dr in dtData.Rows)
                    {
                        string strResult = strFormat;
                        openClassID = dr["oc_id"].ToString();
                        foreach (DataColumn dc in dtData.Columns)
                        {
                            strResult = strResult.Replace(string.Format("[{0}]", dc.ColumnName), dr[dc].ToString());
                        }
                        //插入数据到OpenClass_Detail表中
                        BizDAL.OPENCLASS_DETAIL od = new BizDAL.OPENCLASS_DETAIL();
                        od.oc_id = openClassID;
                        od.content = strResult;
                        od.Insert();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void cboParentClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dtPlugin = BizDAL.digger_plugin.GetList("site_id="+this.cboParentClass.SelectedValue.ToString(), "");
            this.cboChildClass.DisplayMember = "name";
            this.cboChildClass.ValueMember = "plugin_id";
            this.cboChildClass.DataSource = dtPlugin;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.DeleteAllData();
        }
        public void DeleteAllData()
        {
            //删除现有的数据
            BizDAL.OPENCLASS_DETAIL.DeleteAll();
            BizDAL.OPENCLASS.DeleteAll();
            BizDAL.Biz_Keywords.DeleteAll();
            BizDAL.SearchContent.DeleteAll();
        }
        private void btnTransferAll_Click(object sender, EventArgs e)
        {
            //循环数据
            DateTime dtStart = DateTime.Now;
            this.ProcessAllData();
            DateTime dtEnd = DateTime.Now;
            MessageBox.Show(" 转换完毕,共耗时"+dtEnd.Subtract(dtStart).TotalSeconds+"秒");
        }
        public void ProcessAllData()
        {
            DataTable dtParentClas = BizDAL.web_site.GetList("", "");
            DataTable dtChildClass = BizDAL.digger_plugin.GetList("", "");
            for (int i = 0; i < dtParentClas.Rows.Count; i++)
            {
                DataRow[] drs = dtChildClass.Select("site_id="+dtParentClas.Rows[i]["site_id"].ToString());
                for (int j = 0; j < drs.Length; j++)
                {
                    this.TranslateCollectData(dtParentClas.Rows[i]["site_id"].ToString(),dtParentClas.Rows[i]["name"].ToString(), drs[j]["plugin_id"].ToString());
                }
            }
            this.TranslateShowData();


        }

    }
}
